<template>
  <div>
    <el-upload
      :action="uploadUrl"
      :on-change="handleChange"
      :file-list="fileList"
      :auto-upload="false"
    >
      <i class="el-icon-plus"></i>
    </el-upload>

    <el-table :data="paginatedData" style="width: 100%">
      <el-table-column prop="url" label="缩略图">
        <template #default="{ row }">
          <img :src="row.url" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="size" label="大小"></el-table-column>
      <el-table-column prop="type" label="类型"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" type="danger" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-wrapper">
      <el-pagination
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="fileList.length"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      uploadUrl: 'http://localhost:3000/upload',
      fileList: [],
      currentPage: 1,
      pageSize: 5,
    };
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.fileList.slice(start, end);
    },
  },
  
  methods: {
    handleChange(file) {
      const reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = (e) => {
        this.fileList.push({
          name: file.name,
          size: file.size,
          type: file.type,
          url: e.target.result,
        });
        this.uploadFile(file);
      };
    },
    uploadFile(file) {
      const formData = new FormData();
      formData.append('file', file.raw);

      axios.post(this.uploadUrl, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      .then(response => {
        console.log('File uploaded successfully:', response.data);
      })
      .catch(error => {
        console.error('Error uploading file:', error);
      });
    },
    handleDelete(index) {
      this.fileList.splice(index, 1);
    },
    handlePageChange(page) {
      this.currentPage = page;
    },
  },
};
</script>
